package com.dawn.module.infra.api.file;

import cn.hutool.core.util.StrUtil;
import cn.hutool.core.util.URLUtil;
import com.dawn.module.infra.service.file.FileService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;

/**
 * 文件 API 实现类
 *
 * @author dawn
 */
@Service
@Validated
@Slf4j
public class FileApiImpl implements FileApi {

    @Resource
    private FileService fileService;

    @Override
    public String createFile(String name, String path, byte[] content) {
        return fileService.createFile(name, path, content);
    }

    @Override
    public byte[] getFileByUrl(String fileUrl) throws Exception {
        // 获取请求的路径
        String path = StrUtil.subAfter(fileUrl, "/get/", false);
        String str = StrUtil.subBefore(fileUrl, "/get/", false);
        String configId = StrUtil.subAfter(str, "/file/", false);
        log.warn("********** path **********base64String:"+path);
        if (StrUtil.isEmpty(path)) {
            throw new IllegalArgumentException("结尾的 path 路径必须传递");
        }
        if (StrUtil.isEmpty(configId)) {
            throw new IllegalArgumentException("path 路径不合法");
        }
        // 解码，解决中文路径的问题 https://gitee.com/yangyuhua/dawn-hospital/pulls/807/
        path = URLUtil.decode(path);
        // 读取内容
        byte[] content = fileService.getFileContent(Long.valueOf(configId), path);
        if (content == null) {
            log.warn("[getFileContent][configId({}) path({}) 文件不存在]", configId, path);
        }
        return content;
    }

}
